import express from 'express';
import UserModel from "../../mongo/models/user"
import { jwtSign } from "../../utils/jwt"
import { isValidEmail, sendVerificationCodeToEmail } from "../../utils/utils"

const router = express.Router();

const codeMap = new Map();

// 获取验证码
router.post('/user/code', (req, res) => {
    const { username } = req.body;
    const tempData = codeMap.get(username);
    if (tempData) {
        if (tempData.timer + 1000 * 60 * 1 > new Date().getTime()) {
            return res.send({
                code: 400,
                msg: '验证码已发送，请稍后再试'
            })
        }
    }
    if (!username) {
        return res.send({
            code: 400,
            msg: '邮箱不能为空'
        });
    }
    if (!isValidEmail(username)) {
        return res.send({
            code: 400,
            msg: '邮箱格式不正确'
        })
    }
    // 生成 四位数验证码
    const code = Math.floor(Math.random() * 9000) + 1000;
    codeMap.set(username, { code, timer: new Date().getTime() });
    sendVerificationCodeToEmail(username, code+'').then(() => {
        res.send({
            code: 200,
            msg: '验证码发送成功'
        })
    }).catch((err) => {
        res.send({
            code: 400,
            msg: '验证码发送失败'
        })
    })
})

// 注册接口
router.post('/user/register', (req, res) => {
    const { username, password, code } = req.body;
    if (!code) {
        return res.send({
            code: 400,
            msg: '验证码不能为空'
        })
    }
    // 验证验证码
    const codeInfo = codeMap.get(username);
    if (!codeInfo) {
        return res.send({
            code: 400,
            msg: '请先获取验证码'
        })
    }
    if (codeInfo.code+'' !== code) {
        return res.send({
            code: 400,
            msg: '验证码错误！'
        })
    }
    if (codeInfo.timer + 1000 * 60 * 10 < new Date().getTime()) {
        return res.send({
            code: 400,
            msg: '验证码已过期！'
        })
    }
    if (!username || !password) {
        return res.send({
            code: 400,
            msg: '用户名和密码不能为空'
        });
    }

    if (username.length < 6) {
        return res.send({
            code: 400,
            msg: '用户名长度不能小于6'
        });
    }

    if (password.length < 6) {
        return res.send({
            code: 400,
            msg: '密码长度不能小于6'
        });
    }

    const newUser = new UserModel({ username, password });
    newUser.save().then(() => {
        res.send({
            code: 200,
            msg: '注册成功'
        });
        codeMap.delete(username);
    }).catch((err) => {
        res.send({
            err: err.errmsg,
            code: 500,
            msg: '注册失败'
        });
    })
})

// 登录接口
router.post('/user/login', (req, res) => {
    const { username, password } = req.body;

    if (!username || !password) {
        return res.send({
            code: 400,
            msg: '用户名或密码不能为空'
        });
    }

    UserModel.findOne({ username, password }).then((user) => {
        if (user) {
            res.send({
                code: 200,
                msg: '登录成功',
                data: jwtSign({ username: user.username, password: user.password, id: user._id.toString() })
            });
        } else {
            res.send({
                code: 400,
                msg: '用户名或密码错误'
            });
        }
    }).catch(() => {
        res.send({
            code: 500,
            msg: '登录失败'
        });
    })
})

export default router; 